package com.cxm.weilai.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description 调用webService接口方法,返回Json格式的数据。
 * @author zjs
 * @time 2015-12-24 下午3:19:36
 * @version 1.0
 */
public class ObtainDatasourceUtil {
    public static String httpClientPost(String reqUrl, String reqStr) throws Exception {
        URL url = new URL(reqUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        byte[] buf = reqStr.getBytes("UTF-8");
        httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpConn.setRequestMethod("POST");
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        OutputStream out = httpConn.getOutputStream();
        out.write(buf);
        out.flush();
        out.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String reqBody = sb.toString();
        String result = new String(reqBody);
        // 打印返回结果
        return result;

    }

    public static String httpClientGet(String reqUrl, String reqStr) throws Exception {
        URL url = new URL(reqUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String reqBody = sb.toString();
        String result = new String(reqBody);
        // 打印返回结果
        return result;

    }
}
